#include "v_cpu.h"
#include "type.h"

#include <stdlib.h>
#include <stdio.h>

bit8u v_cpu::read_RMW_virtual_byte_32(unsigned segment, bit32u offset) {
	bit32u laddr;
	bit8u data;
	sreg_t *seg = &segment_regs[segment];

	if (seg->sreg_cache.valid & SegAccessROK) {
		if (offset < seg->sreg_cache.u.segment_descriptor.limit) {
			laddr = get_laddr(segment, offset);
			unsigned tlb_index = TLB_INDEX_OF(laddr, 0);
			bit32u lpf = LPFOF(laddr);
			avm_tlb_entry *p_index = &TLB.entry[tlb_index];		

			if (p_index->lpf == lpf) {
				avm_hostpage_addr hostPageAddr = p_index->host_page_addr;
				bit32u page_offset = PAGE_OFFSET(offset);
				bit8u *hostAddr = (bit8u *)(hostPageAddr | page_offset);
				bit8u data = *hostAddr;
				return data;
			
			}
			access_read_linear(laddr, 1, CPL, AVM_RW, (bit8u *)&data);
			return data;
		}
		else {
			printf("Segment limit override.\n");
			exit(0);	
		}
	}
}
